/* Copyright (c) 2004-2024 Peigen.info. All rights reserved. */

package info.peigen.hotpot.component.schedule.core.repository.service;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import info.peigen.hotpot.common.core.enums.YesOrNo;
import info.peigen.hotpot.common.core.result.ResultCode;
import info.peigen.hotpot.common.service.base.exception.BusinessException;
import info.peigen.hotpot.component.data.repository.beetlsql.service.AbstractBeetlSqlRepository;
import info.peigen.hotpot.component.schedule.core.domain.ScheduleNode;
import info.peigen.hotpot.component.schedule.core.domain.action.ScheduleNodeConvertor;
import info.peigen.hotpot.component.schedule.core.repository.entity.ScheduleNodeEntity;
import info.peigen.hotpot.component.schedule.core.repository.mapper.ScheduleNodeMapper;
import lombok.AccessLevel;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.FieldDefaults;
import org.noear.solon.annotation.Component;

import java.util.List;


/**
 * <b>(ScheduleNodeRepository)</b>
 *
 * @author Peigen
 * @version 1.0.0
 * @since 2022/12/28
 */
@Data
@EqualsAndHashCode(callSuper = true)
@FieldDefaults(level = AccessLevel.PRIVATE)
@Component
public class ScheduleNodeRepository extends AbstractBeetlSqlRepository<ScheduleNodeMapper, ScheduleNodeEntity> {

    public void store(ScheduleNode domain) {
        ScheduleNodeEntity entity = ScheduleNodeConvertor.convert(domain);
        mapper.upsert(entity);
    }

    public ScheduleNode active(Integer id) {
        ScheduleNodeEntity entity = getMapper().unique(id);

        Assert.notNull(entity, () -> new BusinessException(ResultCode.FAILURE, "激活失败!id=" + id));

        return ScheduleNodeConvertor.convert(entity);
    }

    public ScheduleNode active(String nodeName) {
        ScheduleNodeEntity entity = getMapper().findByNodeName(nodeName);

        Assert.notNull(entity, () -> new BusinessException(ResultCode.FAILURE, "激活失败!nodeName=" + nodeName));

        return ScheduleNodeConvertor.convert(entity);
    }

    public ScheduleNode activeByIp(String ip) {
        ScheduleNodeEntity entity = getMapper().findByIp(ip);

        if (ObjectUtil.isNull(entity)) {
            return null;
        }

        Assert.notNull(entity, () -> new BusinessException(ResultCode.FAILURE, "激活失败!ip=" + ip));

        return ScheduleNodeConvertor.convert(entity);
    }

    public void offlineNode(DateUnit dateUnit, long value) {
        List<ScheduleNodeEntity> entities = getMapper().findByEnable(YesOrNo.Y);
        entities.forEach(entity -> {
            if (DateUtil.between(entity.getUpdateTime(), DateUtil.date(), dateUnit) > (value * 2)) {
                entity.setYesOrNo(YesOrNo.N);
            }
        });
        saveOrUpdateBatch(entities);
    }
}